package com.knight.async;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

/**
 * 异步处理Controller
 *
 * @author knight
 */
@RestController
public class AsyncController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AsyncController.class);

    @Autowired
    private MockQueue mockQueue;
    @Autowired
    private DeferredResultHolder deferredResultHolder; 

    /**
     * 通过Callable实现
     *
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/order")
    public Callable<String> order() throws InterruptedException {
        LOGGER.info("--主线程开始--");

        Callable<String> callable = () -> {
            LOGGER.info("--子线程开始--");
            Thread.sleep(1000L);
            LOGGER.info("--子线程结束--");
            return "success";
        };

        LOGGER.info("--主线程结束--");
        return callable;
    }


    /**
     * 通过DeferredResult实现异步调用
     *
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/order2/{id}")
    public DeferredResult<String> order2(@PathVariable(value = "id") String id) {
        LOGGER.info("--主线程开始--");
        mockQueue.setPlaceOrder(id);
        DeferredResult<String> deferredResult = new DeferredResult<>();
        deferredResultHolder.getMap().put(id, deferredResult);
        LOGGER.info("--主线程结束--");
        return deferredResult;
    }

}
